package com.chihsien.framework.beans.factory.xml;

import com.chihsien.framework.beans.BeanDefinition;
import com.chihsien.framework.beans.MutablePropertyValues;
import com.chihsien.framework.beans.PropertyValue;
import com.chihsien.framework.beans.factory.support.BeanDefinitionReader;
import com.chihsien.framework.beans.factory.support.BeanDefinitionRegistry;
import com.chihsien.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @auther chihsien on 2021/7/1
 * 针对xml文件进行解析的类
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
   //声明注册表对象
   private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }


    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //dom4j进行xml文件解析
        SAXReader reader = new SAXReader();
        //获取类路径下的配置文件
        InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);

        Document document = reader.read(is);
        //根据docunment对象获取根标签对象beans
        Element rootElement = document.getRootElement();
        //获取根标签下所有的bean标签对象
        List<Element> beanElements = rootElement.elements("bean");
        for (Element beanElement : beanElements) {
            //获取id
            String id = beanElement.attributeValue("id");
            //获取class
            String className = beanElement.attributeValue("class");
            //将id属性和class属性封装刀beanDefinition
                //创建beanDefinition
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);

            //获取bean标签下所有的property标签对象
            List<Element> list = beanElement.elements("property");
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            for (Element element1 : list) {
                String name = element1.attributeValue("name");
                String ref = element1.attributeValue("ref");
                String value = element1.attributeValue("value");
                //封装
                PropertyValue propertyValue = new PropertyValue(name,ref,value);
                //
                mutablePropertyValues.addPropertyValue(propertyValue);
            }
            //将mutablePropertyValues封装进beanDefinition种
            beanDefinition.setPropertyValues(mutablePropertyValues);
            //将beanDefinition对象注册到注册表中
            registry.registerBeanDefinition(id,beanDefinition);
        }
    }
}
